package com.daidai.kafkatest

//import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.DStream
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.{Seconds, StreamingContext}

import scala.collection.mutable

object MyKafkaUtils {

  def main(args: Array[String]): Unit = {

    val conf: SparkConf = new SparkConf().setAppName("sparkStreaming").setMaster("local[*]")
    val streamingContext = new StreamingContext(conf, Seconds(5))


    val kafkaParams = mutable.Map[String, Object](
      "bootstrap.servers" -> "daidai:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "testConsumer",
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    val topics = Array("test")
    val stream = KafkaUtils.createDirectStream[String, String](
      streamingContext,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    val kafkaDStream: DStream[(String, String)] = stream.map(record => (record.key, record.value))

    kafkaDStream.print()

    streamingContext.start()
    streamingContext.awaitTermination()


  }


}
